package com.hl.toolkit.pay.controller;

import com.tencent.common.Configure;
import com.tencent.util.GetWxOrderno;
import com.tencent.util.RequestHandler;
import com.tencent.util.Sha1Util;
import com.tencent.util.TenpayUtil;
import com.tenpay.util.CommonUtil;
import com.tycoin.account.slaveentity.TycoinAccountRecharge;
import com.tycoin.account.slaveservice.TycoinAccountRechargeService;
import com.util.LoadProperties;
import com.util.RandomUtils;
import com.util.StringUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 支付 Author: haolin Email: haolin.h0@gmail.com Date: 2/12/15
 */
@Controller
@RequestMapping("/wx")
public class WepayH5PayScannController {

	private static final Logger log = LoggerFactory.getLogger(WepayH5PayScannController.class);
	
	@Autowired
	private TycoinAccountRechargeService tycoinAccountRechargeService;
 
	@RequestMapping("/app_weixinPay")  
	  public String app_weixinPay(HttpServletRequest request, HttpServletResponse response) throws Exception {  
		 return "/wx/app_weixinPay";
	 	}  
		  
	
	
	@RequestMapping("/goweH5pay")  
	  public void goweH5pay(HttpServletRequest request, HttpServletResponse response) throws Exception {  
  			//共账号及商户相关参数
		 String Charge=request.getParameter("Charge");
		 String userId=request.getParameter("userId");
		 String Logno=request.getParameter("Logno");
		 System.out.println("我的userId是："+userId);
 			String backUri = LoadProperties.loadPropertiesValue("applicationURL")+"/tycoinPayApp/wx/goTowePay.do";
			//授权后要跳转的链接所需的参数一般有会员号，金额，订单号之类，
			//最好自己带上一个加密字符串将金额加上一个自定义的key用MD5签名或者自己写的签名,
			//比如 Sign = %3D%2F%CS% 
			String orderNo="WxTran" + System.currentTimeMillis() + (long) (Math.random() * 1000000L);
			backUri+="?USERID="+userId+"&userId="+userId+"&orderNo="+orderNo+"&money="+Charge+"&Logno="+Logno;
			//URLEncoder.encode 后可以在backUri 的url里面获取传递的所有参数
			backUri = URLEncoder.encode(backUri);
			//scope 参数视各自需求而定，这里用scope=snsapi_base 不弹出授权页面直接授权目的只获取统一支付接口的openid
			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
					"appid=" + Configure.getAppID()+
					"&redirect_uri=" +
					 backUri+
					"&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
			System.out.println("重定向的uri为"+url);
			response.sendRedirect(url);
		 
	 	}  
		  
	@RequestMapping(value="/goTowePay" ,method=RequestMethod.GET)
	 
	public void goTowePay(HttpServletRequest request, HttpServletResponse response, String callback) throws Exception {  
		System.out.println("--------------我进来了goTowePay--------------------");

		//网页授权后获取传递的参数
	 String result="";
				String userId = request.getParameter("userId"); 	
				String orderNo = request.getParameter("orderNo"); 
				String money = request.getParameter("money");
				String code = request.getParameter("code");
				String Logno=request.getParameter("Logno");
				//金额转化为分为单位
 				//商户相关资料 
  				
				String openId ="";
				String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Configure.getAppid()+"&secret="+Configure.getAppSecret()+"&code="+code+"&grant_type=authorization_code";
				
				JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
				System.out.println("------------------------------josnObject="+jsonObject.toString()+"---------------");
				if (null != jsonObject) {
					try{
						openId = jsonObject.getString("openid");
					}catch(Exception e){
						 return;
					}
				}
				
				//获取openId后调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder
				String currTime = String.valueOf(System.currentTimeMillis());
				//8位日期
				String strTime =String.valueOf(System.currentTimeMillis());
				//四位随机数
				String strRandom = TenpayUtil.buildRandom(5) + "";
				//10位序列号,可以自行调整。
				String strReq = strTime + strRandom;
				
				
				//商户号
				String mch_id = Configure.getMchID();
				//子商户号  非必输
				 String sub_mch_id= Configure.getSubMchid();
				//设备号   非必输
				String device_info="000";
				//随机数 
				String nonce_str = strReq;
				//商品描述
				//String body = describe;
				
				//商品描述根据情况修改
				String body = "美食";
				//附加数据
				String attach = userId;
				//商户订单号
				String out_trade_no = orderNo;
				int intMoney = Integer.parseInt(money);
				
				//总金额以分为单位，不带小数点
				int total_fee = intMoney;
				//订单生成的机器 IP
				String spbill_create_ip = request.getRemoteAddr();
				//订 单 生 成 时 间   非必输
//						String time_start ="";
				//订单失效时间      非必输
//						String time_expire = "";
				//商品标记   非必输
//						String goods_tag = "";
				
				//这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
				String notify_url =LoadProperties.loadPropertiesValue("applicationURL")+"/tycoinPayApp/interface/wepayScann/notiy_return";
				System.out.println("异步回调地址：notify_url="+notify_url);
				String trade_type = "JSAPI";
				String openid = openId;
				//非必输
//						String product_id = "";
				SortedMap<String, String> packageParams = new TreeMap<String, String>();
				packageParams.put("appid", Configure.getAppID());  
				packageParams.put("mch_id", mch_id);  
				packageParams.put("nonce_str", nonce_str);  
 				packageParams.put("sub_mch_id", sub_mch_id);  
				packageParams.put("body", body);  
				packageParams.put("attach", attach);  
				packageParams.put("out_trade_no", out_trade_no);  
				
				
				//这里写的金额为1 分到时修改
				packageParams.put("total_fee", money);  
//						packageParams.put("total_fee", "finalmoney");  
				packageParams.put("spbill_create_ip", spbill_create_ip);  
				packageParams.put("notify_url", notify_url);  
				
				packageParams.put("trade_type", trade_type);  
				packageParams.put("openid", openid);  
				
				// RequestHandler：微信支付服务器签名支付请求请求类
				RequestHandler reqHandler = new RequestHandler(request, response);
				reqHandler.init(Configure.getAppID(), Configure.getAppSecret(), Configure.getKey());
				
				// 创建md5摘要
				String sign = reqHandler.createSign(packageParams);
				String xml="<xml>"+
						"<appid>"+Configure.getAppID()+"</appid>"+
						"<mch_id>"+mch_id+"</mch_id>"+
						"<nonce_str>"+nonce_str+"</nonce_str>"+
						"<sign>"+sign+"</sign>"+
						"<sub_mch_id>"+sub_mch_id+"</sub_mch_id>"+
						"<body><![CDATA["+body+"]]></body>"+
						"<attach>"+attach+"</attach>"+
						"<out_trade_no>"+out_trade_no+"</out_trade_no>"+
						//金额，这里写的1 分到时修改
						"<total_fee>"+1+"</total_fee>"+
						//"<total_fee>"+finalmoney+"</total_fee>"+
						"<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>"+
						"<notify_url>"+notify_url+"</notify_url>"+
						"<trade_type>"+trade_type+"</trade_type>"+
						"<openid>"+openid+"</openid>"+
						"</xml>";
				System.out.println(xml);
				String allParameters = "";
				try {
					// 获取package的签名包
					allParameters =  reqHandler.genPackage(packageParams);
				} catch (Exception e) {
					e.printStackTrace();
				}
				// 统一支付接口url
				String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
				System.out.println(" 统一支付接口：createOrderURL="+createOrderURL);

				String prepay_id="";
				try {
					prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);
					if(prepay_id.equals("")){
						request.setAttribute("ErrorMsg", "统一支付接口获取预支付订单出错");
						response.sendRedirect("app_systemFail.jsp");
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				SortedMap<String, String> finalpackage = new TreeMap<String, String>();
				String appid2 = Configure.getAppid();
				// 获取当前时间戳
				String timestamp = Sha1Util.getTimeStamp();
				// 随机数
				String nonceStr2 = nonce_str;
				// 预支付ID
				String prepay_id2 = "prepay_id="+prepay_id;
				String packages = prepay_id2;
				finalpackage.put("appId", appid2);  
				finalpackage.put("timeStamp", timestamp);  
				finalpackage.put("nonceStr", nonceStr2);  
				finalpackage.put("package", packages);  
				finalpackage.put("signType", "MD5");
				// 签名类型
 				 String paySign =  reqHandler.createSign(finalpackage);
  				System.out.println(" -------------------开始进入支付页面----------------");
			 	result=LoadProperties.loadPropertiesValue("applicationURL")+"/tycoinPayApp/wx/app_weixinPay.html?appid="+appid2
			 			+ "&timeStamp="+timestamp
			 			+"&nonceStr="+nonceStr2
			 			+"&package="+packages
			 			+"&sign="+paySign
	 			        +"&signType=MD5";
 				System.out.println("重定向的url:"+result);
long current= System.currentTimeMillis();
				

   			    SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  			    String order_create_time3=formatter3.format(current); 
  			  TycoinAccountRecharge tycoinAccountRecharge=new TycoinAccountRecharge();
  				tycoinAccountRecharge.setPaymentId(orderNo);
 				tycoinAccountRecharge.setDateTime(current);
  				tycoinAccountRecharge.setFee("0");
 				tycoinAccountRecharge.setIsOnline("0");
 				tycoinAccountRecharge.setMoney(money);
 				System.out.println("intMoney:"+intMoney);
 				System.out.println("intMoney/100f:"+intMoney/100.00f);
 				tycoinAccountRecharge.setMoneyfloat(intMoney/100.00f);
  				tycoinAccountRecharge.setUserId(userId);
 				tycoinAccountRecharge.setAddip(spbill_create_ip);
 				tycoinAccountRecharge.setPaymentStatus(0);
 				tycoinAccountRecharge.setPaymentTime(order_create_time3);
 				if(!StringUtil.isNull(Logno)){
	  				tycoinAccountRecharge.setLogno(Logno);
				}else{
	  				tycoinAccountRecharge.setLogno(RandomUtils.getRandomString(16));
				}
 				tycoinAccountRecharge.setPayMode(1);
 			     tycoinAccountRechargeService.save(tycoinAccountRecharge);
 			     System.out.println("MenyFloat"+tycoinAccountRecharge.getMoneyfloat());
				response.sendRedirect(result);
	 	}   
  
 


}
